package com.iteaj.iot.test.server.api;

import com.iteaj.iot.FrameworkComponent;
import com.iteaj.iot.FrameworkManager;
import com.iteaj.iot.IotThreadManager;
import com.iteaj.iot.SocketProtocolFactory;
import com.iteaj.iot.server.ServerComponent;
import com.iteaj.iot.server.ServerProtocolHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static com.iteaj.iot.test.TestConst.LOGGER_API_DESC;

public class ApiServerCloseTestProtocolHandle implements ServerProtocolHandle<ApiServerCloseTestProtocol> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Object handle(ApiServerCloseTestProtocol protocol) {
        logger.info(LOGGER_API_DESC, "FrameworkManager", "register(ProtocolHandle)", "通过");
        int size = FrameworkManager.getInstance().getTimeoutManager().getTimeoutStorages().size();
        IotThreadManager.instance().getExecutorService().schedule(() -> {
            Optional<FrameworkManager.Close> close = FrameworkManager.getInstance().close(ApiTestServerMessage.class);
            if(close.isPresent()) {
                ServerComponent serverComponent = FrameworkManager.getServerComponent(ApiTestServerMessage.class);
                if(serverComponent == null) {
                    logger.info(LOGGER_API_DESC, "FrameworkManager", "close(Class)", "通过");
                } else {
                    logger.error(LOGGER_API_DESC, "FrameworkManager", "close(Class)", "失败");
                }

                FrameworkManager.Close close1 = close.get();
                FrameworkComponent component = close1.getComponent();
                if(component instanceof SocketProtocolFactory) {
                    int size1 = FrameworkManager.getInstance().getTimeoutManager().getTimeoutStorages().size();

                    // 关掉客户端和服务端的Api组件
                    if(size - size1 == 2) {
                        logger.info(LOGGER_API_DESC, "FrameworkManager", "close(Class) + remove(ProtocolTimeoutStorage)", "通过");
                    } else {
                        logger.error(LOGGER_API_DESC, "FrameworkManager", "close(Class) + remove(ProtocolTimeoutStorage)", "失败");
                    }
                }

                Set handles = FrameworkManager.getInstance().getHandleFactory().getHandles(ApiTestServerMessage.class);
                if(handles == null && close1.getHandles().size() != 0) {
                    logger.info(LOGGER_API_DESC, "FrameworkManager", "close(Class) + remove(ProtocolHandle)", "通过");
                } else {
                    logger.error(LOGGER_API_DESC, "FrameworkManager", "close(Class) + remove(ProtocolHandle)", "失败");
                }

            }
        }, 2, TimeUnit.SECONDS);

        return null;
    }
}
